package com.game.base.server.file.qiniulibrary;

import android.os.Handler;
import android.text.TextUtils;

import com.game.base.server.file.qiniulibrary.listener.QiniuUploadListener;
import com.game.base.server.file.qiniulibrary.listener.QiniuUploadMutliListener;
import com.game.base.server.file.qiniulibrary.token.Auth;
import com.game.base.utils.file.FileUtil;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

/**
 * 七牛云存储工具类
 * <p>
 * https://developer.qiniu.com/kodo/sdk/1236/android
 */
public class QiniuiCloudMgr {
    private static Configuration config = new Configuration.Builder()
            .zone(FixedZone.zone0)
            .build();

    private volatile static QiniuiCloudMgr instance = null;
    private UploadManager uploadManager;   // 只需创建一个即可
    private static String token;

    private QiniuiCloudMgr() {
        if (TextUtils.isEmpty(token)) {
            token = Auth.create().uploadToken("meet");
        }
    }

    public static QiniuiCloudMgr getInstance() {
        if (instance == null) {
            synchronized (QiniuiCloudMgr.class) {
                if (instance == null) {
                    instance = new QiniuiCloudMgr();
                }
            }
        }
        return instance;
    }

    private UploadManager getUploadManager() {
        if (uploadManager == null)
            uploadManager = new UploadManager(config);
        return uploadManager;
    }

    /**
     * 上传单个文件
     *
     * @param uploadPathKey 远端文件保存目录  例： blog/yyyyMMdd/用户uid
     *                      自行拼接 " /时间戳.扩展名 "
     */
    public void uploadFile(final String filePath, String uploadPathKey, final QiniuUploadListener uploadListener) {
        if (TextUtils.isEmpty(filePath)) {
            if (uploadListener != null) {
                uploadListener.onUploadEmpty();
            }
            return;
        }

        new Thread(() -> getUploadManager().put(filePath,
                uploadPathKey + "/" + System.currentTimeMillis() + "." + FileUtil.getFileExtension(filePath), token,
                (key, respInfo, jsonData) -> {

                    if (respInfo.isOK()) {
                        String url = "";
                        try {
                            url = UploadType.UPLOAD_URL + jsonData.getString("key"); //外链地址domain + key
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (uploadListener != null) {
                            uploadListener.onUploadSuccess(url);
                        }
                    } else {
                        if (uploadListener != null) {
                            uploadListener.onUploadFail(new Error("上传失败" + respInfo.error));
                        }
                    }
                }, new UploadOptions(null, null, false,
                        (key, percent) -> {
                            //progressbar.setProgress((int) (percent * 100));
                        }, null))).start();
    }

    /**
     * 上传多张图片
     */
    private int i;          //循环变量，表示现在正在上传第几张图片
    private int lost;       // 失败数量
    private List<String> urlList = new ArrayList<>();       // 多张上传文件地址集合

    public void uploadMutliFiles(final List<String> filesUrls, String uploadPathKey, final QiniuUploadMutliListener uploadMutliListener) {
        if (filesUrls != null && filesUrls.size() > 0) {
            urlList.clear();
            i = 0;
            lost = 0;
            final String url = filesUrls.get(i);
            uploadFile(url, uploadPathKey, new QiniuUploadListener() {
                @Override
                public void onUploadSuccess(String url) {
                    urlList.add(url);
                    looperUpload(filesUrls, uploadPathKey, this, uploadMutliListener);
                }

                @Override
                public void onUploadFail(Error error) {
                    lost++;
                    looperUpload(filesUrls, uploadPathKey, this, uploadMutliListener);
                }

                @Override
                public void onUploadEmpty() {
                    looperUpload(filesUrls, uploadPathKey, this, uploadMutliListener);
                }
            });
            return;
        }
        if (uploadMutliListener != null) {
            uploadMutliListener.onUploadEmpty();
        }
    }

    private void looperUpload(List<String> filesUrls, String uploadPathKey, QiniuUploadListener listener, QiniuUploadMutliListener uploadMutliListener) {
        i++;
        if (i < filesUrls.size()) {
            //七牛后台对上传的文件名是以时间戳来命名，以秒为单位，如果文件上传过快，两张图片就会重名而上传失败，所以间隔1秒，保证上传成功
            new Handler().postDelayed(() -> uploadFile(filesUrls.get(i), uploadPathKey, listener), 200);
            return;
        }

        if (uploadMutliListener == null) return;
        // 全部上传失败
        if (lost >= filesUrls.size()) {
            uploadMutliListener.onUploadMutliFail();
        } else {
            uploadMutliListener.onUploadMutliSuccess(urlList);
        }
    }
}
